﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Launcher
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// List column sorter (Sort abc ascending / descending)
        /// </summary>
        private ListViewColumnSorter lvwColumnSorter;
        /// <summary>
        /// The applications working directory, base all paths of this
        /// </summary>
        public string dir = Directory.GetCurrentDirectory();
        /// <summary>
        /// The settings file that contains application specefic settings
        /// </summary>
        public string settings = Directory.GetCurrentDirectory() + @"\\settings.xml";
      
        public Form1()
        {
            InitializeComponent();
            lvwColumnSorter = new ListViewColumnSorter();
            this.listView1.ListViewItemSorter = lvwColumnSorter;
            Image app = Image.FromFile("application.jpg");
            Image img = Image.FromFile("image.jpg");
            Image txt = Image.FromFile("document-text.jpg");
            imageList1.Images.Add(app);
            imageList1.Images.Add(img);
            imageList1.Images.Add(txt);
            
        }
        /// <summary>
        /// Fill the listview with the application details from an xml file
        /// </summary>
        /// <param name="path">The path to the xml file containing the application details</param>
        public void FillAppView(string path)
        {
            
            
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(fs);
            XmlNodeList xmlnode = xmldoc.GetElementsByTagName("Item");

            //Resize the column headers to fit appropriately
            foreach (ColumnHeader ch in this.listView1.Columns)
            {
                ch.Width = -2;
            }


            for (int i = 0; i < xmlnode.Count; i++)
            {

                ListViewItem listviewitem;
                XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

                /*
                 * xmlattrc[i].InnerText contains the name value (The human name of the exe)
                 * xmlnode[i].InnerText contains the path
                 */


                listviewitem = new ListViewItem(xmlattrc["name"].InnerText);
                listviewitem.ImageIndex = (int)int.Parse(xmlattrc["imagekey"].InnerText);
                listviewitem.Tag = xmlnode[i].InnerText;
                listviewitem.SubItems.Add(xmlnode.Item(i).InnerText);
                this.listView1.Items.Add(listviewitem);

            }
            listView1.Tag = path; // for later perhaps?
            xmldoc.Load(settings);
            XmlNode val = xmldoc.SelectSingleNode("Settings/Lastloaded");
            val.InnerText = path;
            xmldoc.Save(settings);
            fs.Close();
            fs.Dispose();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument x = new XmlDocument();
            x.Load(settings);
            XmlNode ll = x.SelectSingleNode("Settings/Lastloaded");
            string path = ll.InnerText;
            if (path.Length > 5)
            {

                FillAppView(path);
            }
        }

       
        /// <summary>
        /// When the listview header is clicked, Sort ascending / descending
        /// </summary>
        private void clicked_(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.listView1.Sort();

        }
        /// <summary>
        /// When a listview item is double clicked, launch that application
        /// </summary>
        private void itemactivated(object sender, EventArgs e)
        {
            System.Windows.Forms.ListView lw = (System.Windows.Forms.ListView)sender;
            string filename = lw.SelectedItems[0].Tag.ToString();

            try
            {
                System.Diagnostics.Process.Start(filename);
            }
            catch
            {
                return;
            }
        }
        /// <summary>
        /// When new task item is clicked under insert item, show the new item form
        /// </summary>
        private void newLaunchItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newitem ni = new newitem(this);
            ni.ShowDialog();
        }

        /// <summary>
        /// When refresh in the context menu is clicked, refresh the listview
        /// </summary>
        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.Refresh();
        }
        /// <summary>
        /// When exit is pressed, exit the application
        /// </summary>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        /// <summary>
        /// Show the options dialog
        /// </summary>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            options o = new options();
            o.ShowDialog(this);
        }
        /// <summary>
        /// Export the contents of the listview as an xml file for later use
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string dir = Directory.GetCurrentDirectory();
            SaveFileDialog s = new SaveFileDialog();
            s.Filter = "Launcher# list|*.xml";
            s.AddExtension = true;
            s.Title = "Save application list";
            s.ShowDialog();
            
            //Some simple error checking
            if(s.FileName != "" && s.FileName.Substring(s.FileName.Length-4,4) == ".xml")
            {
                XmlTextWriter x = new XmlTextWriter(s.FileName, Encoding.UTF8);
                x.Formatting = Formatting.Indented;
                x.WriteStartDocument(true);
                x.WriteComment("Settings file from user: " + Environment.UserName + " exported at: " + DateTime.Now);
                x.WriteStartElement("launcher");
                x.WriteStartElement("Items");
                //Iterate over each item in the listview to save as xml
                foreach (ListViewItem i in listView1.Items)
                {
                    x.WriteStartElement("Item");
                    x.WriteStartAttribute("name");
                    x.WriteString(i.Text);
                    x.WriteEndAttribute();
                    x.WriteStartAttribute("imagekey");
                    x.WriteValue(i.ImageIndex);
                    x.WriteEndAttribute();
                    x.WriteString(i.Tag.ToString());
                    x.WriteEndElement();
                }
                x.WriteEndElement();
                x.WriteEndElement();
                x.WriteEndDocument();
                x.Close();
            }
        }
        /// <summary>
        /// Open an xml file generated by Launcher#
        /// </summary>
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Launcher# application list|*.xml";
            open.Title  = "Open application list";
            open.ShowDialog();
            open.CheckFileExists = true;
            if (open.FileName != "")
            {
                // Then the file is valid
                FillAppView(open.FileName);
                
            }
        }
        /// <summary>
        /// Delete all items in the listview
        /// </summary>
        private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you really want to delete all items? This can not be reversed!", "Delete all items?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                /*
                XmlDocument xd = new XmlDocument();
                xd.Load(listView1.Tag.ToString()); // The tag contains the filepath
                 */
                listView1.Items.Clear();
            }
            
        }
        
        //TODO: Implement deletion of selected item
        /// <summary>
        /// Delete selected item from list and xml file
        /// </summary>
        private void deleteSelectedToolStripMenuItem_Click(object sender, EventArgs e)
        {

            ListViewItem selected = listView1.SelectedItems[0];
            if ( MessageBox.Show("Are you sure you want to delete this item?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                selected.Remove();
                /*
                XmlDocument xd = new XmlDocument();
                XmlNodeList x = xd.GetElementsByTagName("Item");
                 */
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 ab = new AboutBox1();
            ab.ShowDialog(this);
        }
    }
}
